import { writeFileSyncIfChanged } from "@stackframe/stack-shared/dist/utils/fs";
import { deindent, stringCompare } from "@stackframe/stack-shared/dist/utils/strings";
import * as fs from "fs";
import * as path from "path";

async function main() {
  let quetzalKeys, supportedLocales
  try {
    quetzalKeys = JSON.parse(fs.readFileSync(path.join(__dirname, "../quetzal-translations/keystore.json"), 'utf-8'));
    supportedLocales = JSON.parse(fs.readFileSync(path.join(__dirname, "../quetzal-translations/supported-locales.json"), 'utf-8'));
  } catch (e: unknown) {
    console.warn('Quetzal translation files not found, assuming Quetzal failed. The translations will not be updated.');
    process.exit(0);
  }
  
  const locales = Object.fromEntries(await Promise.all(supportedLocales.map(async (locale) => [
    locale,
    JSON.parse(fs.readFileSync(path.join(__dirname, `../quetzal-translations/${locale}.json`), 'utf-8'))
  ] as const)));

  // replace Quetzal's auto-generated IDs (like k-0, k-1, etc.) with our own
  // we do this because Quetzal's IDs are not stable when running the script multiple times
  const oldKeysReversed = Object.fromEntries(Object.entries(quetzalKeys).map(([key, value]) => [value, key]));
  const newKeys = Object.fromEntries(Object.keys(sortKeys(quetzalKeys)).map((key, i) => [key, `__stack-auto-translation-${i}`]));
  const newKeysReversed = Object.fromEntries(Object.entries(newKeys).map(([key, value]) => [value, key]));
  const localesByKeys = Object.fromEntries(Object.entries(locales).map(([key, value]) => [
    key,
    Object.fromEntries(Object.entries(value).map(([key, value]) => [newKeys[oldKeysReversed[key]], value]))
  ]));

  const enUS = localesByKeys["en-US"];
  for (const [key, enUSTranslation] of Object.entries(enUS)) {
    if (newKeysReversed[key] !== enUSTranslation) {
      throw new Error(`Quetzal's en-US translation of ${JSON.stringify(newKeysReversed[key])} is different from the original string! Quetzal's translation: ${JSON.stringify(enUSTranslation)}`);
    }
  }

  writeFileSyncIfChanged("src/generated/quetzal-translations.ts", deindent`
    // THIS FILE IS AUTO-GENERATED BY THE \`merge-quetzal-translations.ts\` SCRIPT.
    // DO NOT EDIT IT BY HAND.

    import { typedEntries } from "@stackframe/stack-shared/dist/utils/objects";


    export const quetzalKeys = new Map(typedEntries(${JSON.stringify(sortKeys(newKeys), null, 2)} as const));


    export const quetzalLocales = new Map(typedEntries({
      ${[...supportedLocales].sort().map(locale => deindent`
        ${JSON.stringify(locale)}: new Map(typedEntries(${JSON.stringify(sortKeys(localesByKeys[locale]), null, 2)} as const)),
      `).join("\n")}
    } as const));
  ` + "\n");
}

main().catch(err => {
  console.error(err);
  process.exit(1);
});



function sortKeys<T extends Record<string, any>>(obj: T): T {
  return Object.fromEntries(Object.entries(obj).sort((a, b) => stringCompare(a[0], b[0]))) as T;
}
